package com.sea.base.ext.global

import android.annotation.SuppressLint
import android.content.Context
import android.net.ConnectivityManager
import android.net.ConnectivityManager.NetworkCallback
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import androidx.core.content.ContextCompat
import androidx.lifecycle.MutableLiveData
import com.sea.base.ext.obs.smartPost

/**
 * 监听见[onNetworkStatusChanged]
 */
@SuppressLint("MissingPermission")
fun isAvailableNetwork(context: Context): Boolean {
    //偶尔出现联网了但值是false的情况，这里只取值是true的状态
    val onNetworkStatusChanged = onNetworkStatusChanged(context)
    if (onNetworkStatusChanged.value == true) {
        return true
    }

    val cm = ContextCompat.getSystemService(context, ConnectivityManager::class.java) ?: return false
    val net = cm.getNetworkCapabilities(cm.activeNetwork)
    return net?.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) ?: false
}

@SuppressLint("MissingPermission")
private fun onNetworkStatusChanged(context: Context) = run {
    val ld = MutableLiveData<Boolean>()
    (context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager)
        .registerNetworkCallback(NetworkRequest.Builder().build(), object : NetworkCallback() {
            override fun onAvailable(network: Network) {
                ld.smartPost(true)
            }

            override fun onLost(network: Network) {
                ld.smartPost(false)
            }
        })
    return@run ld
}
